<template>
  <a-drawer
    :title="title"
    :maskClosable="false"
    :visible="visible"
    :destroyOnClose="true"
    :width="800"
    :body-style="{
      height: 'calc(100% - 110px)',
      boxSizing: 'border-box',
      overflowY: 'auto',
    }"
    @close="closeModal"
  >
    <a-form layout="vertical">
      <a-row :gutter="12">
        <a-col :span="24">
          <a-card title="基本信息" size="small">
            <a-row :gutter="12" :wrap="true">
              <a-col :span="12">
                <a-form-item label="同住人姓名" v-bind="validateInfos.name">
                  <a-input
                    placeholder="请输入同住人姓名"
                    v-model:value="modelRef.name"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item
                  label="证件类型"
                  v-bind="validateInfos.idcard_type"
                >
                  <a-input-group compact :style="{ display: 'flex' }">
                    <a-select
                      class="search-select"
                      v-model:value="modelRef.idcard_type"
                      :options="idcardOption"
                    />
                    <a-input
                      v-model:value="modelRef.idcard"
                      placeholder="请输入证件号码"
                    />
                  </a-input-group>
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="性别" v-bind="validateInfos.sex">
                  <a-select
                    v-model:value="modelRef.sex"
                    placeholder="请选择"
                    :options="sexOption"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="手机号码" v-bind="validateInfos.phone">
                  <a-input
                    v-model:value="modelRef.phone"
                    placeholder="请输入手机号码"
                  />
                </a-form-item>
              </a-col>
            </a-row>
          </a-card>
        </a-col>
        <a-col :span="24">
          <a-card class="mt-10" title="证件照片" size="small">
            <div class="card-content">
              <a-popover
                placement="bottom"
                v-for="(item, index) in cardImg"
                :key="index"
                :visible="item.visible"
                @visibleChange="
                  (show) => {
                    if (!modelRef.idcard_img[item.key] || !show) {
                      item.visible = show;
                    }
                  }
                "
              >
                <template #content>
                  <PhotoUpload
                    @request="$utils.commonRequest"
                    :staticPathes="$utils.staticPathes"
                    :imgAction="$utils.imgAction"
                    :token="$store.getters.token"
                    accept="image/jpg,image/jpeg,image/gif,image/png"
                    @successPhoto="
                      (url) => {
                        successPhoto(url, item.key);
                      }
                    "
                  />
                </template>
                <div v-if="!modelRef.idcard_img[item.key]" class="card-box">
                  <div class="card-upload">
                    <img :src="`${item.src}`" />
                    <span class="font-gary">{{ item.title }}</span>
                  </div>
                </div>
                <div v-else class="card-img">
                  <img class="img" :src="modelRef.idcard_img[item.key]" />
                  <div class="mask">
                    <a-space>
                      <a :href="modelRef.idcard_img[item.key]" target="_blank">
                        <EyeOutlined class="icon"
                      /></a>
                      <DeleteOutlined
                        class="icon"
                        @click="
                          () => {
                            modelRef.idcard_img[item.key] = '';
                          }
                        "
                      />
                    </a-space>
                  </div>
                </div>
              </a-popover>
            </div>
            <div class="tips font-gary">
              <span class="tips-title">温馨提示：</span
              >支持识别身份证正面覆盖填入基本信息，点击身份证人像面，选择身份证正面图片后上传即可。
            </div>
          </a-card>
        </a-col>
      </a-row>
    </a-form>
    <div class="drawer-footer">
      <a-button @click.prevent="closeModal" class="mr-10">关闭</a-button>
      <a-button type="primary" @click.prevent="onSubmit"> 保存同住人 </a-button>
    </div>

    <!-- 识别替换 -->
    <a-modal
      :visible="resultVisible"
      title="是否需要覆盖提取的内容"
      :destroyOnClose="true"
      okText="覆盖"
      @ok="handleUpdateText"
      @cancel="resultVisible = false"
    >
      <p>
        姓名：<span class="link" @click="handleTextCopy(resultInfo.name)">{{
          resultInfo.name
        }}</span>
      </p>
      <p>
        证件号码：<span class="link" @click="handleTextCopy(resultInfo.id)">{{
          resultInfo.id
        }}</span>
      </p>
      <p v-if="resultInfo.gender">
        性别：<span>{{ resultInfo.gender }}</span>
      </p>
    </a-modal>
  </a-drawer>
</template>

<script>
import {
  defineComponent,
  ref,
  computed,
  watch,
  reactive,
  toRaw,
  toRefs,
} from "vue";
import { Form, message } from "ant-design-vue";
import request from "@/common/utils/request";
const useForm = Form.useForm;
import { CARD_OPTIONS, SEX_OPTIONS } from "@/common/utils/constant";
import utils from "@/common/utils/utils";
import { PhotoUpload } from "bl-common-vue3";
import { DeleteOutlined, EyeOutlined } from "@ant-design/icons-vue";
import _ from "lodash";
export default defineComponent({
  name: "AddInmate",
  components: {
    PhotoUpload,
    DeleteOutlined,
    EyeOutlined,
  },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    info: {
      type: Object,
      default: () => ({}),
    },
  },
  setup(props, { emit }) {
    //   标题
    const title = computed(() => {
      return _.isEmpty(props.info) ? "添加同住人" : "编辑同住人";
    });

    const state = reactive({
      sexOption: SEX_OPTIONS,
      idcardOption: CARD_OPTIONS,
      cardImg: [
        {
          src: utils.staticPath + "images/contract/renxiang.png",
          title: "上传身份证人像面",
          key: "front_url",
        },
        {
          src: utils.staticPath + "images/contract/guohui.png",
          title: "上传身份证国徽面",
          key: "back_url",
        },
        {
          src: utils.staticPath + "images/contract/shouchi.png",
          title: "上传手持身份证照",
          key: "hand_url",
        },
      ],
      resultInfo: {},
      resultVisible: false,
    });

    /**
     * @description:  表单
     */
    const modelRef = reactive({
      name: "",
      phone: "",
      idcard: "", // 证件号码
      idcard_type: "idcard", // 证件类型
      idcard_img: {
        front_url: "",
        back_url: "",
        hand_url: "",
      },
      sex: 1,
    });
    const rulesRef = reactive({
      name: [{ required: true, message: "必填项" }],
      phone: [
        {
          required: true,
          validator: (rules, value) => utils.phoneValidator(rules, value),
        },
      ],
    });

    const { resetFields, validate, validateInfos } = useForm(
      modelRef,
      rulesRef
    );

    const successPhoto = (data, key) => {
      const { url } = data;
      if (url && key === "front_url") {
        // 读取身份证信息
        request
          .post("/third", "/wxapp/tool/cvOcr/idCard", {
            file: url,
            failNoMsg: true,
          })
          .then((res) => {
            if (res?.idCard?.name && res?.idCard?.id) {
              state.resultInfo = res.idCard;
              state.resultVisible = true;
            }
          });
      }
      modelRef.idcard_img[key] = url;
    };

    const handleUpdateText = () => {
      modelRef.name = state.resultInfo.name;
      modelRef.idcard = state.resultInfo.id;
      if (state.resultInfo?.gender) {
        // 替换性别
        let sex = state.sexOption.filter(
          (v) => v.label == state.resultInfo.gender
        );
        if (sex?.length && sex[0]?.value) {
          modelRef.sex = sex[0].value;
        }
      }
      state.resultVisible = false;
      state.resultInfo = {};
    };

    const handleTextCopy = (item) => {
      utils.copyText(item);
    };

    const closeModal = () => {
      emit("addCancel");
    };

    const onSubmit = () => {
      validate().then(() => {
        let submitInfo = _.cloneDeep(modelRef);
        if (_.isEmpty(props.info)) {
          // 添加
          emit("add", submitInfo);
        } else {
          // 编辑
          emit("edit", submitInfo);
        }
      });
    };

    const setModelRef = (state) => {
      for (let key in state) {
        modelRef[key] = state[key];
      }
    };
    // 初始化
    const init = () => {
      if (!_.isEmpty(props.info)) {
        setModelRef(props.info);
      }
    };

    watch(
      () => props.visible,
      (val) => {
        if (val) {
          init();
        } else {
          resetFields();
          state.resultInfo = {};
        }
      }
    );

    return {
      title,
      modelRef,
      validateInfos,
      ...toRefs(state),
      closeModal,
      onSubmit,
      successPhoto,
      handleUpdateText,
      handleTextCopy,
    };
  },
});
</script>

<style lang="less" scoped>
.search-select {
  :deep(.ant-select-selector) {
    width: 110px !important;
  }
}
.card-box {
  width: 200px;
  height: 140px;
  padding: 10px 30px;
  background-color: #f7f7f7;
  margin-right: 16px;
  border-radius: 12px;
  cursor: pointer;
  .card-upload {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    align-items: center;
    img {
      width: 100%;
      object-fit: contain;
    }
  }
}
.card-content {
  display: flex;
}

.card-img {
  width: 200px;
  height: 140px;
  border-radius: 12px;
  padding: 8px;
  background: #fafafa;
  margin-right: 16px;
  cursor: pointer;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  position: relative;
  .img {
    width: 100%;
    object-fit: contain;
    overflow: hidden;
    border-radius: 5px;
  }
  .mask {
    position: absolute;
    top: 0px;
    left: 0;
    width: 200px;
    height: 140px;
    border-radius: 12px;
    display: none;
    justify-content: center;
    align-items: center;
    background: rgba(0, 0, 0, 0.4);
    cursor: default;
    .icon {
      color: #fff;
      cursor: pointer;
      font-size: 16px;
    }
    -webkit-transition: all 0.5s;
    transition: all 0.5s;
  }

  &:hover {
    .mask {
      display: flex;
    }
  }
}
.font-gary {
  color: #999;
}
.tips {
  margin-top: 40px;
  background-color: #f5f7fa;
  line-height: 40px;
  padding: 0 10px;
  .tips-title {
    color: #636467;
  }
}
</style>
